package language.basic.exception;

import lombok.extern.slf4j.Slf4j;

import java.io.PrintStream;
import java.text.ParseException;

//在main方法中打印的异常调用栈，哪怕异常是在外层被捕获，依然会将出问题的方法throwyichang()显示在第一行
//说明外层抛异常不会吞掉异常调用栈信息，而且最上层的at 是离问题最近的地方。
//catch the language.basic.exception
//        java.lang.ArrayIndexOutOfBoundsException: 144
//        at exceptionStackTraceShow.throwExcption(exceptionStackTraceShow.java:22)
//        at exceptionStackTraceShow.main(exceptionStackTraceShow.java:12)
@Slf4j
public class exceptionStackTraceShow {
    public static void main(String[] args) {
        PrintStream printStreamForOut = createLoggingWrapper(System.out, false);
        PrintStream printStreamForErr = createLoggingWrapper(System.err, true);
        System.setOut(printStreamForOut);
        System.setErr(printStreamForErr);

        try {
            int[] ints = new int[10];
            int a  = ints[144];
        } catch (Exception e) {
            System.out.println(e.getMessage()); //144
            System.out.println(e.toString()); //java.lang.ArrayIndexOutOfBoundsException: 144
            e.printStackTrace(); //e.printStackTrace()的信息是最全的它包括e.toString()和对战信息，并且输出到System.err
//            log.info("end!");
        }
    }

    public static void throwExcption() throws ParseException {
        int[] ints = new int[10];
        int a  = ints[144];
    }

    public static PrintStream createLoggingWrapper(final PrintStream printStream, final boolean isErr) {
        return new PrintStream(printStream) {
            @Override
            public void print(final String string) {
                if (!isErr){
                    log.debug(string);
                }else{
                    log.error(string);
                }
            }
        };
    }
}
